<?php


namespace app\service;


use think\swoole\Table;

/**
 * Class Atomic
 * @package app\service
 * Waring 数据存于内存中,如果服务重启数据会丢失,注意离线存储,仅做示例参考.
 */
class Atomic
{
    private $atomoc;

    public function __construct(Table $table)
    {
        $this->atomoc = $table->get('vote');
    }

    private function check(string $uid): void
    {
        if ($this->atomoc->exist($uid) == false) {
            $this->set($uid);
        }
    }

    public function set(string $uid): void
    {
//        $this->atomoc->set($uid, ['poll' => 0,'icon'=>'']);
        $this->atomoc->set($uid, ['poll' => 0]);
    }

    public function add(string $uid, int $step = 1): int
    {
        $this->check($uid);
        return $this->atomoc->incr($uid, 'poll', $step);
    }

    public function sub(string $uid, int $step = 1): int
    {
        $this->check($uid);
        return $this->atomoc->decr($uid, 'poll', $step);
    }

    public function get(string $uid): int
    {
        $this->check($uid);
        return $this->atomoc->get($uid, 'poll');
    }

    public function cancelled(string $uid): void
    {
        if ($this->atomoc->exist($uid)) {
            $this->atomoc->del($uid);
        }
    }

    public function all(): array
    {
        $data = [];
        foreach ($this->atomoc as $uid => $item) {
            $data[$uid] = $this->atomoc->get($uid);
        }
        arsort($data);
        return $data;
    }
}